//
//  Firma2InterventoViewController.m
//  InterventixApp
//
//  Created by Diego Falcinelli on 22/05/13.
//
//

#import "Firma2InterventoViewController.h"
#import "NSData+Conversion.h"
#import <CoreGraphics/CoreGraphics.h>
#import <ImageIO/CGImageProperties.h>
#import <ImageIO/CGImageSource.h>
#import <MobileCoreServices/UTCoreTypes.h>

@interface Firma2InterventoViewController ()

@end

@implementation Firma2InterventoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(IBAction) indietro{
    
    
    //self.intervento.firma = UIImageJPEGRepresentation(self.firma.image,0.1);
    
    self.intervento.firma = [self generate1BitGIF:self.firma.image];
	
    [[self navigationController] popViewControllerAnimated:YES];
}

- (NSData *) generate1BitGIF: (UIImage *) image
{
    NSMutableData *retData = [[NSMutableData alloc]initWithCapacity:0];
    //NSURL* destUrl = [ NSURL fileURLWithPath: @"/Users/username/Desktop/test.gif" ];
    
   // CGImageDestinationRef dst = CGImageDestinationCreateWithURL( (CFURLRef) CFBridgingRetain(destUrl), kUTTypeGIF, 1, NULL );
    
    CGImageDestinationRef dst = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)(retData), kUTTypeGIF, 1, NULL);
    
    const uint8_t colorTable[ 6 ] = { 0, 0, 0, 255, 255, 255 };
    NSData* colorTableData = [ NSData dataWithBytes: colorTable length: 6 ];
    
    NSDictionary* gifProps = [ NSDictionary dictionaryWithObject: colorTableData
                                                          forKey: (NSString*) kCGImagePropertyGIFImageColorMap ];
    
    NSDictionary* imgProps = [ NSDictionary dictionaryWithObject: gifProps
                                                          forKey: (NSString*) kCGImagePropertyGIFDictionary ];
    
    CGImageDestinationAddImage( dst, image.CGImage, (CFDictionaryRef) CFBridgingRetain(imgProps) );
    CGImageDestinationFinalize( dst );
    CFRelease( dst );
    
    
    //NSBitmapImageRep *bitmap = [NSBitmapImageRep imageRepWithData: imgData];
    
    return retData;
    
    //return CFBridgingRelease(CGImageCreateCopyWithColorSpace((__bridge CGImageRef)(image),CGColorSpaceCreateDeviceGray()));
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        //buttonhome a sinistra
        
    }
    if(toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
        //buttonhome a destra
    }
    if(toInterfaceOrientation == UIInterfaceOrientationPortrait){
        //buttonhome sotto
    }
    if(toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
        //buttonhome sopra
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dimensionePennello = 4.0;
    self.colorePennello = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    self.ultimoPunto = [touch locationInView:self.firma];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [touches anyObject];
    CGPoint puntoCorrente = [touch locationInView:self.firma];
    
    
    // definiamo il contest grafico
    UIGraphicsBeginImageContext(self.firma.frame.size);
    [self.firma.image drawInRect:CGRectMake(0, 0, self.firma.frame.size.width, self.firma.frame.size.height)];
    // settiamo la forma e la dimensione del pennello
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), self.dimensionePennello);
    // convertiamo il colore e impostiamolo come colore del pennello
    const CGFloat *components = CGColorGetComponents([self.colorePennello CGColor]);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), components[0], components[1], components[2], components[3]);
    // disegna il percorso
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), self.ultimoPunto.x, self.ultimoPunto.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), puntoCorrente.x, puntoCorrente.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    // settiamo il disegno appena creato
    self.firma.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    self.ultimoPunto = puntoCorrente;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self touchesMoved:touches withEvent:event];
}

- (IBAction)cancella{
    self.firma.image = nil;
}

@end
